Page({
  data: {
    code: '',
    name: '',
    price: 0,
    quantity: 0,
    type: 'buy',
    balance: 0,
    canBuyMax: 0,
    canSellMax: 0
  },
  async onLoad(options) {
    // 【关键】股票名参数解码，防止中文显示乱码
    const code = options.code;
    const name = options.name ? decodeURIComponent(options.name) : '';
    const price = Number(options.price) || 0;
    this.setData({ code, name, price });

    const openid = (await wx.cloud.callFunction({ name: 'getOpenId' })).result.openid;
    const db = wx.cloud.database();
    const user = await db.collection('user').where({ openid }).get();
    let balance = 100000;
    if (user.data.length && user.data[0].balance !== undefined) balance = user.data[0].balance;
    this.setData({ balance });

    const posRes = await db.collection('positions').where({ openid, code }).get();
    this.setData({
      canSellMax: posRes.data.length ? posRes.data[0].quantity : 0,
      canBuyMax: Math.floor(balance / this.data.price)
    });
  },
  onInputQuantity(e) {
    this.setData({ quantity: parseInt(e.detail.value) || 0 });
  },
  onTypeChange(e) {
    this.setData({ type: e.detail.value });
  },
  async onTrade() {
    const { type, code, name, price, quantity, balance } = this.data;
    if (quantity <= 0) {
      wx.showToast({ title: '请输入数量', icon: 'none' }); return;
    }
    const openid = (await wx.cloud.callFunction({ name: 'getOpenId' })).result.openid;
    const db = wx.cloud.database();
    let newBalance = balance;
    if (type === 'buy') {
      const cost = price * quantity;
      if (cost > balance) {
        wx.showToast({ title: '资金不足', icon: 'none' }); return;
      }
      newBalance -= cost;
      const posRes = await db.collection('positions').where({ openid, code }).get();
      if (posRes.data.length) {
        await db.collection('positions').doc(posRes.data[0]._id).update({
          data: {
            quantity: posRes.data[0].quantity + quantity,
            cost: ((posRes.data[0].quantity * posRes.data[0].cost + cost) / (posRes.data[0].quantity + quantity)).toFixed(2)
          }
        });
      } else {
        await db.collection('positions').add({ data: { openid, code, name, quantity, cost: price } });
      }
    } else if (type === 'sell') {
      const posRes = await db.collection('positions').where({ openid, code }).get();
      if (!posRes.data.length || posRes.data[0].quantity < quantity) {
        wx.showToast({ title: '持仓不足', icon: 'none' }); return;
      }
      newBalance += price * quantity;
      const leftQty = posRes.data[0].quantity - quantity;
      if (leftQty > 0) {
        await db.collection('positions').doc(posRes.data[0]._id).update({ data: { quantity: leftQty } });
      } else {
        await db.collection('positions').doc(posRes.data[0]._id).remove();
      }
    }
    await db.collection('trades').add({
      data: {
        openid, code, name, type, price, quantity, amount: price * quantity,
        time: new Date().toLocaleString()
      }
    });
    await db.collection('user').where({ openid }).update({ data: { balance: newBalance } });
    wx.showToast({ title: '交易成功', icon: 'success' });
    wx.navigateBack();
  }
});
